package com.itfreer.forestry.manage;

import com.itfreer.data.syn.DataSynItemService;
import com.itfreer.forestry.manage.token.DockTokenInter;
import com.itfreer.forestry.manage.token.common.MinglingOutPut;
import com.itfreer.power.user.entity.UserInfoEntity;
import com.itfreer.utils.json.JsonUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.util.Map;

/**
 * Created by 2020/12/12
 *
 * @author yangyang
 */
@Component("UserInforSynService")
public class UserInforSynService implements DataSynItemService {

    private String convert(UserInfoEntity userInfoEntity) {
        StringBuffer json = new StringBuffer();
        json.append("{");
        json.append("\"owerId\":\"" + userInfoEntity.getId() + "\",");
        json.append("\"owerName\":\"" + userInfoEntity.getUserName() + "\",");
        json.append("\"mobile\":\"" + userInfoEntity.getTel() + "\",");

        String code =getArrayString(userInfoEntity.getDepartmentId());
        code =code.substring(1, code.length() - 1);
        json.append("\"code\":\"" + code + "\",");
        String townName = getArrayString(userInfoEntity.getDepartmentName());

        townName =  townName.substring(1, townName.length() - 1);
        json.append("\"townName\":\"" + townName + "\",");

        String villageCode = getArrayString(userInfoEntity.getAdminDepartment());
        villageCode = villageCode.substring(1, villageCode.length() - 1);
        json.append("\"villageCode\":\"" + villageCode + "\",");
        String villageName = getArrayString( userInfoEntity.getAdminDepartmentName());
        villageName = villageName.substring(1, villageName.length() - 1);
        json.append("\"villageName\":\"" + villageName + "\"");
        json.append("}");
        return json.toString();
    }
    public String add(Object o, String s) {
        DockTokenInter.initToken();
        HttpClient httpclient = HttpClientBuilder.create().build();
        try{
            UserInfoEntity depEntity = JsonUtils.toBean((String) o, UserInfoEntity.class);
            URI uri=new URI(MinglingOutPut.getBaseUrl() + "/api/patrol/oAuth2/savePatrolRanger");
            HttpPost httpPost = new HttpPost(uri);

            httpPost.setHeader("Authorization","Bearer " + MinglingOutPut.token);

            String json = convert(depEntity);
            //请求参数
            StringEntity toentity = new StringEntity(json, ContentType.TEXT_PLAIN.APPLICATION_JSON);
            toentity.setContentEncoding("UTF-8");
            toentity.setContentType("application/json");
            httpPost.setEntity(toentity);

            HttpResponse result = httpclient.execute(httpPost);
            String message = getResult(result);
            return message;
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }

    public String update(Object o, String s) {
        DockTokenInter.initToken();
        HttpClient httpclient = HttpClientBuilder.create().build();
        try{
            UserInfoEntity depEntity = JsonUtils.toBean((String) o, UserInfoEntity.class);
            URI uri=new URI(MinglingOutPut.getBaseUrl() + "/api/patrol/oAuth2/updatePatrolRanger");
            HttpPost httpPost = new HttpPost(uri);

            httpPost.setHeader("Authorization","Bearer " + MinglingOutPut.token);

            String json = convert(depEntity);
            //请求参数
            StringEntity toentity = new StringEntity(json, ContentType.TEXT_PLAIN.APPLICATION_JSON);
            toentity.setContentEncoding("UTF-8");
            toentity.setContentType("application/json");
            httpPost.setEntity(toentity);

            HttpResponse result = httpclient.execute(httpPost);
            String message = getResult(result);
            return message;
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }

    public String delete(String s, String s1) {
        DockTokenInter.initToken();
        HttpClient httpclient = HttpClientBuilder.create().build();
        try{
            URI uri=new URI(MinglingOutPut.getBaseUrl() + "/api/patrol/oAuth2/deletePatrolRanger?owerId=" + s1);
            HttpDelete httpPost = new HttpDelete(uri);

            httpPost.setHeader("Authorization","Bearer " + MinglingOutPut.token);

            HttpResponse result = httpclient.execute(httpPost);
            String message = getResult(result);
            return message;
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }

    public String getResult(HttpResponse result) throws IOException {
        if (result.getStatusLine().getStatusCode() == 200) {
            System.out.println("请求成功");
            String str = "";
            // 读取服务器返回过来的json字符串数据
            str = EntityUtils.toString(result.getEntity());

            // 把json字符串转换成json对象，方便操作
            String jsonResult = JsonUtils.toJSONString(str);
            Map<?, ?> map = JsonUtils.toBean(str, Map.class);
            if ("200".equals(map.get("status").toString())) {
                return null;
            }
            // 查询返回的参数是List<List<String>>格式
            return jsonResult;
        } else {
            System.out.println("请求失败");
            return "请求失败";
        }
    }


    protected String getArrayString(String[] items) {
        if (items == null) {
            return null;
        } else if (items.length <= 0) {
            return "";
        } else {
            String test = ",";
            String[] var3 = items;
            int var4 = items.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                String item = var3[var5];
                if (item != null && !item.equals("")) {
                    test = test + item + ",";
                }
            }

            return test;
        }
    }
}
